package com.zoke.password.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.warpdrive.multiplestatuslayout.MultipleStatusLayout;
import com.zoke.password.Conf;
import com.zoke.password.R;
import com.zoke.password.adapter.PasswordAdapter;
import com.zoke.password.base.BaseActivity;
import com.zoke.password.base.BaseDialog;
import com.zoke.password.dialog.AppLoading;
import com.zoke.password.dialog.NormalDialog;
import com.zoke.password.model.Password;
import com.zoke.password.model.Result;
import com.zoke.password.model.User;
import com.zoke.password.tools.PwdCheckUtil;
import com.zoke.password.tools.UToast;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import io.nebulas.Constants;
import io.nebulas.api.SmartContracts;
import io.nebulas.model.ContractModel;
import io.nebulas.model.GoodsModel;
import io.nebulas.utils.Util;

@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener,
        BaseQuickAdapter.RequestLoadMoreListener,
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemLongClickListener {


    @ViewInject(R.id.swipe)
    SwipeRefreshLayout swipeRefreshLayout;
    @ViewInject(R.id.recycler)
    RecyclerView recyclerView;
    @ViewInject(R.id.iv_settings)
    ImageView iv_settings;
    @ViewInject(R.id.iv_back)
    ImageView iv_back;

    private PasswordAdapter passwordAdapter;
    private List<Password> mList = new ArrayList<>();


    private Password delPwd;

    private String password = "";

    private Password toPwd;


    //执行网络请求
    private AppLoading loading;
    private String serialNumber = "";
    private boolean isDo = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loading = new AppLoading(this, false, R.string.loading);
        iv_settings.setVisibility(View.VISIBLE);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setImageResource(R.drawable.ic_settings);
        iv_settings.setImageResource(R.drawable.ic_add);
        swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.baseColor));
        swipeRefreshLayout.setOnRefreshListener(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        passwordAdapter = new PasswordAdapter(mList);
        passwordAdapter.openLoadAnimation();
        passwordAdapter.setOnItemClickListener(this);
        passwordAdapter.setOnItemLongClickListener(this);
        recyclerView.setAdapter(passwordAdapter);
        swipeRefreshLayout.setRefreshing(true);
        getPasswordList();
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        if (mImmersionBar != null)
            mImmersionBar.statusBarDarkFont(true)
                    .statusBarView(R.id.status)
                    .init();
    }

    @Event({R.id.iv_settings, R.id.iv_back, R.id.btn_save})
    private void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.iv_settings:
                AddActivity.open(this);
                break;
            case R.id.iv_back:
                open(MainActivity.this, SettingsActivity.class);
                break;
            case R.id.btn_save:
                open(MainActivity.this, AddActivity.class);
                break;
        }
    }

    @Override
    public void onRefresh() {
        getPasswordList();
    }

    @Override
    public void onLoadMoreRequested() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PatternLockActivity.LOCK:
                if (data != null) {
                    password = User.getUser().password;
                    PasswordDetailActivity.open(this, toPwd);
                } else {
                    LogUtil.e("data=" + data);
                }
                break;
            case AddActivity.ADD:
                if (data != null) {
                    String json = data.getStringExtra("json");
                    LogUtil.e("json=" + json);
                    Password password = new Gson().fromJson(json, Password.class);
                    password.level = PwdCheckUtil.checkPassword(password.password);
                    mList.add(password);
                    passwordAdapter.notifyDataSetChanged();
                }
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        toPwd = mList.get(position);
        if (TextUtils.isEmpty(password)) {
            //校验是否是本人
            PatternLockActivity.open(this, 0);
            return;
        }
        PasswordDetailActivity.open(this, toPwd);
    }

    private void getPasswordList() {
        ContractModel contractModel = new ContractModel();
        contractModel.args = Arrays.toString(new Object[]{});//notice: Arrays.toString() was need , if not : {"error":"json: cannot unmarshal array into Go value of type string"}
        contractModel.function = "getPasswordList";
        String from = User.getUser().address;
        SmartContracts.call(contractModel, from, Conf.SMART, 1, new SmartContracts.StatusCallback() {
            @Override
            public void onSuccess(final String response) {
                LogUtil.e("response:" + response);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(false);
                        if (TextUtils.isEmpty(response)) return;
                        try {
                            JSONObject object = new JSONObject(response);
                            JSONObject result = object.getJSONObject("result");
                            String res = result.optString("result");
                            if (TextUtils.isEmpty(res)) return;
                            List<Password> list = new Gson().fromJson(res, new TypeToken<List<Password>>() {
                            }.getType());
                            if (list == null || list.size() == 0) {
                                //展示空页面
                                UToast.show(MainActivity.this, R.string.error);
                                return;
                            }
                            mList.clear();
                            mList.addAll(list);
                            for (Password pwd : mList) {
                                pwd.level = PwdCheckUtil.checkPassword(pwd.password);
                            }
                            passwordAdapter.notifyDataSetChanged();
                        } catch (JSONException e) {
                            LogUtil.e(e.toString());
                        }

                    }
                });
            }

            @Override
            public void onFail(final String error) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        UToast.show(MainActivity.this, MainActivity.this.getString(R.string.error) + ":" + error);
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });

            }
        });
    }

    @Override
    public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
        delPwd = mList.get(position);
        new NormalDialog(MainActivity.this).setOk(new NormalDialog.OnViewListener() {
            @Override
            public void onViewClick(View view, BaseDialog dialog) {
                del(delPwd.id);
                //执行删除操作
                dialog.dismiss();
            }
        }).show();
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isDo) {
            nasQueryTransferStatus();
        }

    }


    public void nasQueryTransferStatus() {
        isDo = false;
        if (TextUtils.isEmpty(serialNumber)) {
            if (loading != null) loading.dismiss();
            return;
        }
        SmartContracts.queryTransferStatus(Constants.MAIN_NET, serialNumber, new SmartContracts.StatusCallback() {
            @Override
            public void onSuccess(final String response) {
                LogUtil.e("onSuccess :" + response);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (loading != null) loading.dismiss();
                        if (TextUtils.isEmpty(response)) {
                            UToast.show(MainActivity.this, R.string.del_error);
                            return;
                        }
                        Result result = new Gson().fromJson(response, Result.class);
                        if (result == null) {
                            UToast.show(MainActivity.this, R.string.del_error);
                            return;
                        }
                        if (result.code != 0) {
                            UToast.show(MainActivity.this, MainActivity.this.getString(R.string.del_error) + ":" + result.msg);
                            return;
                        }
                        //执行删除成功的操作
                        if (delPwd != null) {
                            mList.remove(delPwd);
                            passwordAdapter.notifyDataSetChanged();
                        }
                        UToast.show(MainActivity.this, R.string.del_success);
                    }
                });
            }

            @Override
            public void onFail(final String error) {
                LogUtil.e("onFail " + error);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (loading != null) loading.dismiss();
                        UToast.show(MainActivity.this, MainActivity.this.getString(R.string.del_error) + ":" + error.toString());
                    }
                });
            }
        });
    }

    private void del(int id) {
        //执行删除操作
        isDo = true;
        if (loading != null) loading.show();
        //一次请求对应一个码
        serialNumber = Util.getRandomCode(Constants.RANDOM_LENGTH);
        GoodsModel goods = new GoodsModel();
        goods.name = "删除";
        goods.desc = "-执行删除云备份信息";
        String functionName = "delPassword";
        //password, preference
        String[] args = new String[]{id + ""};
        SmartContracts.call(this, Constants.MAIN_NET, goods, functionName, Conf.SMART, Conf.VALUE, args, serialNumber);

    }

}
